<?php

namespace Api\Controller;
use Think\Controller;

class AgentController extends HomeController
{
    //获取用户openid
    public function getOpenid(){
        $wx_config=C('WECHAT_CONF');
        $code = I('get.code');
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$wx_config['appid']."&secret=".$wx_config['appsecret']."&js_code=".$code."&grant_type=authorization_code";
        $wx_return = curl_get($url);  // 一个使用curl实现的get方法请求
        $wx_return = json_decode($wx_return,true);
        $log_name= "wx.log";
        if(empty($wx_return)){
            log_result($log_name,"微信返回信息为空");
            $this->ajaxReturn(['status'=>0,'info'=>"微信返回信息为空"]);
            die();
        }else{
           $logfail=array_key_exists('errcode',$wx_return);
           if($logfail){
               log_result($log_name,"错误: ".$wx_return['errmsg']);
               $this->ajaxReturn(['status'=>0,'info'=>"错误: ".$wx_return['errmsg']]);
               die();
           }else{
               $signature = $_GET['signature'];
               $signature2 = sha1($_GET['rawData'].$wx_return['session_key']);  //记住不应该用TP中的I方法，会过滤掉必要的数据
               if ($signature != $signature2) {
                   $this->ajaxReturn(['status'=>0,'info'=>"数据签名验证失败"]);
               }
             $this->login($wx_return);
           }
        }
    }

    //登录，查询用户表中是否存在openid，如果不存在就重新生成一条
    private function login($wx_data){
      $user=M('agent')->where(array('wx_openid'=>$wx_data['openid']))->find();
      if(empty($user)){
           $data['wx_openid']=$wx_data['openid'];
           $data['nickname']=I('get.nickname');
           $data['avatar']=I('get.avatarUrl');
           $data['status']=1;
           $data['last_login_time']=time();
           $res=D('Agent')->register($data);
           if($res>0){
               $data['uid']=$res;
               //将用户信息保存在session中，session的key由是不唯一的字符串
               $this->createToken($data);
           }else{
               $this->ajaxReturn(['status'=>0,'info'=>"服务器错误"]);
           }

      }else{
          $this->createToken($user);
      }

    }

    private function createToken($data){
        $session3rd  = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;
        for($i=0;$i<16;$i++){
            $session3rd .=$strPol[rand(0,$max)];
        }
        S($session3rd,$data,86400);
        $this->ajaxReturn(['status'=>1,'user'=>$data,'session_key'=>$session3rd]);
    }


    public function mycenter(){
        $session_key=I('get.session_key');
        $uid=is_wxlogin($session_key);
        $user=M('agent')->where(array('uid'=>$uid))->find();
        if(!empty($user)){
            $user['articleNum']=M('info')->where(array('user_id'=>$uid))->count();
            $user['resNum']=M('comment')->where(array('uid'=>$uid))->count();
            $bgimg['background']=__ROOT__ . '/Public/Api/images/background.png';
            $bgimg['cash_btn']=__ROOT__ . '/Public/Api/images/cash_btn.png';
            $bgimg['cash_submit']=__ROOT__ . '/Public/Api/images/cash_submit.png';
            $this->ajaxReturn(['status'=>1,'info'=>$user,'bgimg'=>$bgimg]);
        }else{
            $this->ajaxReturn(['status'=>0,'info'=>"用户不存在"]);
        }
    }


    //我的帖子
    public function myArticle(){
        $session_key=I('get.session_key');
        $user= S($session_key);
        if(!empty($user)){
            $info=M('info')->where(array('user_id'=>$user['uid']))->order('create_time desc')->field('id,cate_id,des,create_time')->select();
            foreach ($info as &$v){
                $v['iconSrc']=$user['avatar'];
                $v['create_time']=date('Y-m-d',$v['create_time']);
                $v['title']=M('cate')->where(array('id'=>$v['cate_id']))->getField('name');
            }
            $this->ajaxReturn(['status'=>1,'info'=>$info,'count'=>count($info)]);
        }else{
            $this->ajaxReturn(['status'=>0,'info'=>"用户没有登录"]);
        }

    }

    /**已采纳的帖子
     * 我对一篇帖子发表了评论，别人采纳了我这条评论，这个帖子就是被采纳的帖子
     */
    public function adoptArticle(){
        $session_key=I('get.session_key');
        $user= S($session_key);
        if(!empty($user)){
            $comment=M('comment')->where(array('uid'=>$user['uid'],'status'=>1))->select();
            $info_ids=array();
            foreach ($comment as $k=>$v){
                array_push($info_ids,$v['info_id']);
            }
            $info=M('info')->where(array('id'=>array('in',$info_ids)))->order('create_time desc')->field('id,title,des,create_time')->select();
            foreach ($info as &$v){
                $v['iconSrc']=$user['avatar'];
                $v['create_time']=date('Y-m-d',$v['create_time']);
            }
            $this->ajaxReturn(['status'=>1,'info'=>$info,'count'=>count($info)]);
        }else{
            $this->ajaxReturn(['status'=>0,'info'=>"用户没有登录"]);
        }

    }


    public function systemMsg(){
        $session_key=I('get.session_key');
        $user= S($session_key);
        if(!empty($user)){
            $info=M('webinfo')->where(array('receiver_id'=>$user['uid']))->field('cate,count(*) as count')->group('cate')->select();
            foreach ($info as $k=>&$v){
                $first=M('webinfo')->where(array('receiver_id'=>$user['uid'],'cate'=>$v['cate']))->order('send_time desc')->limit(1)->select();
                $v['content']=$first[0]['title'];
                switch ($v['cate']){
                    case 1:
                        $v['title']='帖子删除';
                        $v['icon']='../../images/systemMsg/t1.png';
                    break;
                    case 2:
                        $v['title']='帖子评论';
                        $v['icon']='../../images/systemMsg/t.png';
                    break;
                }
            }
            $this->ajaxReturn(['status'=>1,'info'=>$info,'count'=>count($info)]);
        }else{
            $this->ajaxReturn(['status'=>0,'info'=>"用户没有登录"]);
        }
    }


    public function Cash(){
        if(IS_POST){
            $data=I('post.');
            $uid=is_wxlogin($data['session_key']);
            if($uid){
                $user=M('agent')->where(array('uid'=>$uid))->find();
                if(empty($user)){
                    $this->ajaxReturn(['status'=>0,'msg'=>"用户不存在"]);
                    die();
                }
                if($user['balance']<intval($data['money'])){
                    $this->ajaxReturn(['status'=>0,'msg'=>"用户余额不足"]);
                    die();
                }

                $appid = "wxf8100719019ca8bf";//商户账号appid
                $mch_id = "1508035801";//商户号
                $key = "4B2fNrP25pwY2n5XkzcjaRa8SMx4kM56";
                $openid=$user['wx_openid'];//授权用户openid

                //获取订单号
                $order_id=getOrderSn();

                $arr = array();
                $arr['mch_appid'] = $appid;
                $arr['mchid'] = $mch_id;
                $arr['nonce_str'] =time().rand(100000, 999999);//随机字符串，不长于32位
                $arr['partner_trade_no'] = $order_id;//商户订单号
                $arr['openid'] = $openid;
                $arr['check_name'] = 'NO_CHECK';//是否验证用户真实姓名，这里不验证
                $arr['amount'] = $data['money']*100;//付款金额，单位为分
                $arr['desc'] =$user['nickname']."提现".$data['money'];//描述信息
                $arr['spbill_create_ip'] = $_SERVER['SERVER_ADDR'];//获取服务器的ip


                $order['orderid']=$order_id;
                $order['userid']=$uid;
                $order['ordtime']=time();
                $order['cash_account']=$user['wx_account'];
                $order['ordtitle']=$arr['desc'];
                $order['ordfee']=$data['money'];
                $order['payment_type']=1;
                $order['status']=0;



                $arr['sign'] = $this->MakeSign($arr,$key);//签名

                $wget = $this->ArrToXml($arr);//数组转XM

                $re=M('cash')->add($order);

                //开启事务
                M()->startTrans();

                $pay_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';//api地址
                $xml = $this->postData($pay_url,$wget);//发送数据

                $row1=M('agent')->where(array('uid'=>$uid))->setDec('balance',intval($data['money']));

                $rdata = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
                $return_code = (string)$rdata->return_code;
                $result_code = (string)$rdata->result_code;
                $return_code = trim(strtoupper($return_code));
                $result_code = trim(strtoupper($result_code));

                if ($return_code == 'SUCCESS' && $result_code == 'SUCCESS') {
                    $data2['paytime']=$rdata->payment_time;
                    $data2['payment_trade_no']=$rdata->payment_no;
                    $data2['status']=1;
                    $row2=M("cash")->where(array('orderid'=>$order_id))->save($data2);
                    if($row1!==false && $row2!==false){
                        //事务提交
                        M()->commit();
                        $isrr = array(
                            'status'=>1,
                            'msg' => "提现成功",
                        );
                    }else{
                        //事务回滚
                        M()->rollback();
                        $isrr = array(
                            'status'=>0,
                            'msg' => "提现成功,订单修改失败",
                        );
                    }

                } else {
                    M()->rollback();
                    $returnmsg = (string)$rdata->return_msg;
                    $isrr = array(
                        'status' => 0,
                        'msg' => $returnmsg,
                    );
                }
                $this->ajaxReturn($isrr);
            }else{
                $this->ajaxReturn(['status'=>0,'info'=>"用户没有登录"]);
            }

        }

    }


    //数组转XML
  private  function ArrToXml($arr)
    {
        if(!is_array($arr) || count($arr) == 0) return '';
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($arr)
    {
        $buff = "";
        foreach ($arr as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    private function MakeSign($arr,$key){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    //发送数据
   private  function postData($url,$postfields){
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $postfields;
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        //以下是证书相关代码
        $params[CURLOPT_SSLCERTTYPE] = 'PEM';
        $params[CURLOPT_SSLCERT] =getcwd().'/ThinkPHP/Library/Vendor/Wxpay/apiclient_cert.pem';//绝对路径
        $params[CURLOPT_SSLKEYTYPE] = 'PEM';
        $params[CURLOPT_SSLKEY] =getcwd().'/ThinkPHP/Library/Vendor/Wxpay/apiclient_key.pem';//绝对路径
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }



}